import {
	requestUrl
} from '../../config/env'

module.exports = (url, method, data, header = {}) => {
	return new Promise((resolve, reject) => {
		const defaultOptions = {
			//#ifdef H5|APP
			merchant_id: 28,
			from:'h5'
			//#endif
			// #ifdef MP-WEIXIN
			appid: uni.getAccountInfoSync().miniProgram.appId
			// #endif
		};
		let finalData = {
			...data,
			...defaultOptions,
		};

		if (uni.getStorageSync('token')) {
			finalData.token = uni.getStorageSync('token');
		}
		let onLaunchData = uni.getStorageSync('onLaunchData')
		if (onLaunchData) {
			finalData = {
				...onLaunchData,
				...finalData,
			};
		}

		let finalHeader = {
			"Content-Type": data && data.contentType ? data.contentType : (header.contentType ? header
				.contentType : "application/json"),
			"Authorization": uni.getStorageSync('token')
		}

		uni.request({
			url: requestUrl() + url,
			method: method,
			data: finalData, // 将finalData作为请求的数据参数传递
			header: finalHeader,

			success(res) {
				if (res.data.code === 200) {
					resolve(res.data)
				} else if (res.data.code === 401) {
					// 获取用户代理字符串
					// #ifdef APP|H5
					// uni.setStorageSync('token', '');
					// //h5 oauth2 登录逻辑
					// const appId = 'wxacd3f9be8282b278'; // 替换为你的 AppID
					// const redirectUri = encodeURIComponent('https://soft.511m.com/h5_callback'); // 替换为你的回调页面 URL
					// const scope = 'snsapi_userinfo'; // 授权作用域，snsapi_userinfo 可获取用户详细信息
					// const state = '我是自定义'; // 自定义的状态参数，用于防止 CSRF 攻击
					// const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
								
					// window.location.href = authUrl;
					uni.navigateTo({
						url: '/pages/user/loginByUsername',
					})
				
					reject('请重新登录')
					// #endif
					
					// #ifdef MP-WEIXIN
					uni.navigateTo({
						url: '/pages/WXLogin/WXLogin',
					})
					console.log('到了微信登录')
					reject('请重新登录')
					// #endif


				} else if (res.data.code == 302) {
					uni.showToast({
						icon: 'error',
						title: res.data.message
					})

					setTimeout(function() {
						if (res.data.jump_type == 'reLaunch') {
							uni.reLaunch({
								url: res.data.jump,
							})
						} else {
							uni.navigateTo({
								url: res.data.jump,
							})
						}

					}, 1000)

				} else {
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 10000
					})
					resolve(res.data)
				}
			},
			fail(err) {

				reject(err,'请求失败了')
			}
		})
	})
}